/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CaseCompiler.java
 *
 * Created on Feb 22, 2012, 11:47:22 PM
 */
package casecompiler;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import mylittleinvestigations.CaseInformation.Case;
import mylittleinvestigations.CaseInformation.CaseParseException;
import mylittleinvestigations.CaseInformation.CaseParser;
import org.dawnmew.jpurewave.SoundSystem;
import org.dawnmew.simplejar.JarBuilder;
import org.newdawn.slick.SlickException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 *
 * @author Luke
 */
public class CaseCompiler extends javax.swing.JFrame {

    /** Creates new form CaseEditor */
    public CaseCompiler() {
        BouncyCastleProvider provider = new BouncyCastleProvider();
        Security.addProvider(provider);
        
        initComponents();
        SoundSystem.getInstance().cutAudioLines();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu3 = new javax.swing.JMenu();
        jMenu4 = new javax.swing.JMenu();
        fileChooser = new javax.swing.JFileChooser();
        compileButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        sourceTextArea = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        privateExponentTextField = new javax.swing.JTextField();
        jMenuBar3 = new javax.swing.JMenuBar();
        jMenu5 = new javax.swing.JMenu();
        openMenuItem = new javax.swing.JMenuItem();
        jMenu6 = new javax.swing.JMenu();

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        jMenu3.setText("File");
        jMenuBar2.add(jMenu3);

        jMenu4.setText("Edit");
        jMenuBar2.add(jMenu4);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Case Compiler");

        compileButton.setText("Compile!");
        compileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                compileButtonActionPerformed(evt);
            }
        });

        sourceTextArea.setColumns(20);
        sourceTextArea.setRows(5);
        jScrollPane1.setViewportView(sourceTextArea);

        jLabel2.setText("Private exponent:");
        jLabel2.setToolTipText("");

        jMenu5.setText("File");

        openMenuItem.setText("Open");
        openMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openMenuItemActionPerformed(evt);
            }
        });
        jMenu5.add(openMenuItem);

        jMenuBar3.add(jMenu5);

        jMenu6.setText("Edit");
        jMenuBar3.add(jMenu6);

        setJMenuBar(jMenuBar3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(compileButton, javax.swing.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(privateExponentTextField)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(privateExponentTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(compileButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed
        int returnVal = fileChooser.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            File file = fileChooser.getSelectedFile();

            try
            {
                sourceTextArea.read(new FileReader(file.getAbsolutePath()), null);
            }
            catch (IOException ex)
            {
                System.out.println("problem accessing file"+file.getAbsolutePath());
            }
        }
}//GEN-LAST:event_openMenuItemActionPerformed

private void compileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compileButtonActionPerformed
        try
        {
            CaseParser.ParseCase(sourceTextArea.getText());
            Case.getInstance().SetPrivateExponent(privateExponentTextField.getText());
            Case.getInstance().markChildSprites();
            
            File stagingFolder = Paths.get("CaseStagingFolder").toAbsolutePath().toFile();
            
            if (stagingFolder.exists() && stagingFolder.isDirectory())
            {
                RecursivelyDeleteDirectory(stagingFolder);
            }
            
            if (!Files.exists(stagingFolder.toPath()))
            {
                Files.createDirectory(stagingFolder.toPath());
            }
            
            Case.getInstance().SaveToXml(stagingFolder.toString(), "case.xml");
            Case.getInstance().SaveMetadataToXml(stagingFolder.toString(), "caseMetadata.xml");
            JarBuilder jarBuilder = new JarBuilder("case1.mlicase");
            jarBuilder.setVerboseMode(true);
            jarBuilder.addFolderFromDisk(stagingFolder.toString(), "", true);
            jarBuilder.close();
            
            RecursivelyDeleteDirectory(stagingFolder);
        }
        catch (CaseParseException ex)
        {
            Logger.getLogger(CaseCompiler.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (SlickException ex)
        {
            Logger.getLogger(CaseCompiler.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex)
        {
            Logger.getLogger(CaseCompiler.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_compileButtonActionPerformed

    public static void RecursivelyDeleteDirectory(File fileOrDirectory)
    {
        if (fileOrDirectory.isDirectory())
        {
            String[] children = fileOrDirectory.list();
            
            for (String child : children)
            {
                RecursivelyDeleteDirectory(new File(fileOrDirectory, child));
            }
        }

        // If we've reached this stage, then either this is a file,
        // or it's a directory that is empty.  Either way, we can delete it.
        fileOrDirectory.delete();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CaseCompiler.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CaseCompiler.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CaseCompiler.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CaseCompiler.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CaseCompiler().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton compileButton;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenu jMenu6;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JMenuBar jMenuBar3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JTextField privateExponentTextField;
    private javax.swing.JTextArea sourceTextArea;
    // End of variables declaration//GEN-END:variables
}
